package com.fuatnow.game.handler;

import com.fuatnow.game.manager.MessageManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.fuatnow.game.constant.ProtocolConstant.ENTER_MINESWEEP;

/**
 * Created by fuatnow on 17/2/10.
 */
public class GateMineSweepConnectionHandler extends SimpleChannelInboundHandler<String>
{
    private static final Logger logger = LoggerFactory.getLogger(GateMineSweepConnectionHandler.class);
    private static ChannelHandlerContext _gateMineSweepConnection = null;

    public static ChannelHandlerContext getGateMineSweepConnection() {
        return _gateMineSweepConnection;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String message) throws Exception
    {
//        logger.info("------------------------>"+message);
        JSONObject jo = new JSONObject(message);
        int cmdID = jo.getInt("cmdID");
        if(cmdID == ENTER_MINESWEEP)
        {
            _gateMineSweepConnection = channelHandlerContext;
            logger.info("[Gate-minesweep] connection is established");
            sendGreet2Auth();
        }
        else
        {
            MessageManager.getInstance().processMessage(channelHandlerContext,message);
        }
    }

    private void sendGreet2Auth()
    {
        _gateMineSweepConnection.writeAndFlush("Hello,我是gate");
    }
}
